package com.ytzl.gotrip.service.impl;
import com.alibaba.dubbo.config.annotation.Reference;
import com.ytzl.gotrip.ext.utils.RedisUtils;
import com.ytzl.gotrip.model.GotripUser;
import com.ytzl.gotrip.rpc.api.RpcGotripUserService;
import com.ytzl.gotrip.rpc.api.RpcSendEmailService;
import com.ytzl.gotrip.service.GotripUserService;
import com.ytzl.gotrip.service.SendEmailService;
import com.ytzl.gotrip.utils.common.Constants;
import com.ytzl.gotrip.utils.common.DigestUtil;
import com.ytzl.gotrip.utils.common.EmptyUtils;
import com.ytzl.gotrip.utils.common.ErrorCode;
import com.ytzl.gotrip.utils.exception.GotripException;
import com.ytzl.gotrip.vo.userinfo.ItripUserVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@Service("sendEmailService")
public class SendEmailServiceImpl implements SendEmailService {
    @Reference
    private RpcSendEmailService rpcSendEmailService;
    @Reference
    private RpcGotripUserService rpcGotripUserService;
    @Resource
    private RedisUtils redisUtils;
    private Logger LOG= LoggerFactory.getLogger(GotripUserServiceImpl.class);

    public GotripUser findByUserCode(String userCode) throws Exception {
        //校验数据
        if(EmptyUtils.isEmpty(userCode)){
            throw new GotripException("用户Code不能为空", ErrorCode.AUTH_PARAMETER_ERROR);

        }
        Map<String,Object> param=new HashMap<>();
        param.put("userCode",userCode);
        System.out.println(param);

        List<GotripUser> gotripUserList = rpcGotripUserService.getGotripUserListByMap(param);
        System.out.println(gotripUserList.size());

        return EmptyUtils.isEmpty(gotripUserList)?null
                : gotripUserList.get(0);
    }

    @Override
    public void validateEmail(String user, String code) throws Exception {
        //验证邮箱是否正确
        if (!validEmail(user)) {
            throw new GotripException("请输入正确邮箱格式",ErrorCode.AUTH_PARAMETER_ERROR);
        }
        //验证用户是否存在
        GotripUser u= this.findByUserCode(user);
        if (EmptyUtils.isEmpty(u)) {
            throw new GotripException("用户不存在",ErrorCode.AUTH_PARAMETER_ERROR);
        }
        //获取redis中存储的短信验证码
        String key=Constants.RediskeyPrefix.ACTIVATION_PHONE + user;
        String cacheCode=(String) redisUtils.get(key);
        if (EmptyUtils.isEmpty(cacheCode)||!cacheCode.equals(code)) {
            throw new GotripException("代码已失效",ErrorCode.AUTH_PARAMETER_ERROR);
        }
        //激活用户
        u.setActivated(1);
        u.setUserType(0);
        u.setFlatID(u.getId());
        rpcGotripUserService.updateGotripUser(u);
        //用户激活成功
        LOG.info("用户激活成功----》",user);
    }

    @Override
    public void registerByEamil(ItripUserVO itripUserVO) throws Exception {
        //数据校验
        checkRegisterData(itripUserVO);
        //验证手机号
        if (!validEmail(itripUserVO.getUserCode())) {
            throw  new GotripException("邮箱格式不正确", ErrorCode.AUTH_PARAMETER_ERROR);
        }
        GotripUser byUserCode = this.findByUserCode(itripUserVO.getUserCode());
        if (!EmptyUtils.isEmpty(byUserCode)) {
            throw  new GotripException("用户已存在",ErrorCode.AUTH_PARAMETER_ERROR);
        }
        //构建用户信息
        GotripUser gotripUser=new GotripUser();
        BeanUtils.copyProperties(itripUserVO,gotripUser);
        gotripUser.setActivated(0);
        //数据加密
        String md5UserPassword= DigestUtil.hmacSign(gotripUser.getUserPassword());
        gotripUser.setUserPassword(md5UserPassword);
        //数据入库
        Integer integer = rpcGotripUserService.insertGotripUser(gotripUser);
        //发送短信验证码
        int code = DigestUtil.randomCode();

        //将验证码保存到redis中
        String key= Constants.RediskeyPrefix.ACTIVATION_PHONE+gotripUser.getUserCode();
        redisUtils.set(key,""+code,60*30);
        rpcSendEmailService.sendEmail(itripUserVO.getUserCode(),"gotrip激活码",""+code);
    }

    public void checkRegisterData(ItripUserVO itripUserVO) throws GotripException {
        if ( EmptyUtils.isEmpty(itripUserVO)){
            throw new GotripException("请传入数据",ErrorCode.AUTH_PARAMETER_ERROR);
        }
        if (EmptyUtils.isEmpty(itripUserVO.getUserCode())) {
            throw new GotripException("用户账号不能为空",ErrorCode.AUTH_PARAMETER_ERROR);
        }

        if (EmptyUtils.isEmpty(itripUserVO.getUserName())) {
            throw new GotripException("用户昵称不能为空",ErrorCode.AUTH_PARAMETER_ERROR);
        }
        if (EmptyUtils.isEmpty(itripUserVO.getUserPassword())) {
            throw new GotripException("用户密码不能为空",ErrorCode.AUTH_PARAMETER_ERROR);
        }
    }
    private boolean validEmail(String email){

        String regex="^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$"  ;
        return Pattern.compile(regex).matcher(email).find();
    }
}
